package com.mvw.tetrominoes.data {
	
	/**
	 * An abstract representation of a two-dimensional plane using a multi-dimensional Array.
	 */
	public class Plane {
		
		private var _plane:Array;
		private var _height:int;
		private var _width:int;
		
		/**
		 * The constructor initializes the Plane as an empty 2D Array.
		 * 
		 * @param y The number of rows in the Plane.
		 * @param x The number of cells in a row.
		 */
		public function Plane(y:int, x:int):void {
			_height = y;
			_width = x;
			_plane = new Array(y);
			for (var line:int = 0; line < _plane.length; line++) {
				_plane[line] = new Array(x);
			}
		}
		
		/**
		 * Returns total height of plane.
		 * 
		 * @return The number of rows in the Plane.
		 */
		public function get height():int {
			return _height;
		}
		
		/**
		 * Returns total width of plane.
		 * 
		 * @return The number of cells in a row.
		 */
		public function get width():int {
			return _width;
		}
		
		/**
		 * Sets a Cell at a given position.
		 * 
		 * @param index The x position.
		 * @param index The y position.
		 * @param value The Object to be set.
		 */
		public function setCellAt(y:int, x:int, value:Object):void {
			try {
				_plane[y][x] = value;
			}
			catch (error:Error) {
				//do nothing
			}
		}
		
		/**
		 * Returns if a Cell is at a given position.
		 * 
		 * @param x The x position.
		 * @param y The y position.
		 * 
		 * @return An instance of Boolen.
		 */
		public function isCellAt(y:int, x:int):Boolean {
			try {
				if (y < 0) {
					return false;
				}
				else if (x >= 0 && x < width && y < height) {
					return (_plane[y][x] != null);
				}
				else {
					return true;
				}
			}
			catch (error:Error) {
				return true;
			}
			return true;
		}
		
		/**
		 * Returns a Cell is at a given position.
		 * 
		 * @param x The x position.
		 * @param y The y position.
		 * 
		 * @return An Object.
		 */
		public function getCellAt(y:int, x:int):Object {
			return _plane[y][x];
		}
		
		/**
		 * Loops through the Plane and removes empty lines.
		 * 
		 * @param An Array indicating which lines to remove.
		 */
		public function compress(emptylines:Array):void {
			for (var emptyline:int = 0; emptyline < emptylines.length; emptyline++) {
				if (!isNaN(emptylines[emptyline])) {
					var lastline:Array = new Array(width);
					for (var line:int = 0; line <= emptylines[emptyline]; line++) {
						var currentline:Array = _plane[line];
						_plane[line] = lastline;
						lastline = currentline;
					}
				}
			}
		}
		
	}
}